package com.gaoxk.distributeReq;


import com.gaoxk.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *  对接口进行处理: 适配多个接口
 * @className: WebserverHandlerInterceptor
 * @copyright: Copyright (C) 2019-2028, Inc. All rights reserved.
*/

//@Component
public class WebserverHandlerInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

/**
     * 在controller处理之前首先对请求参数进行处理，以及对公共参数的保存
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String path = request.getRequestURI();
        //logger.info("111111111111111");
        logger.info("WebserverHandlerInterceptor|调用开始");
        logger.info("外部请求路径[{}]",path);

        //根据不同的 请求报文头 数据  去请求不同的接口
        //是某接口的时候进入
        //应用已注册侦听器的 preHandle 方法。
        //返回：
        //如果执行链应继续处理下一个侦听器或处理程序本身，则为 true。
        // 否则，DispatcherServlet 假定此拦截器已经处理了响应本身，则为false
        if (path.contains("/BONDService/cxf")) {
            //logger.info("haoahoaoahaohaohoahoa");
            //获取头部的参数  ServiceID  此id对应的就是接口的真实地址。直接转到对应地址处理即可
            //获取请求参数
            RequestWrapper requestWrapper = new RequestWrapper(request);
            String reqstr = requestWrapper.getBody();
            //logger.info("WebserverHandlerInterceptor123123|{}", reqstr);
            //去对应的服务码。因为这个xml 尝试转document失败。直接字符串截取的方式获得
            String serverId =getServiceId(reqstr);
            String svcScn = getSvcScn(reqstr);
            logger.info("ServiceID:[{}],SvcScn:[{}]",serverId,svcScn);
            //如果不为空，去掉后两位，因为后两位是 子服务码
            /*if (StringUtils.isNotEmpty(serverId)){
                serverId = serverId.substring(0,serverId.length()-2);
            }*/
            //获取导serverid 之后拼装接口请求地址 转到对应的地址去  讲fssc替换为 servieid
//            if(serverId.equals("30062000020")){
//                path = path.replaceAll("/BONDService/cxf", "/ESBService/test1");
//            }else if(serverId.equals("30064000001")){
//                path = path.replaceAll("/BONDService/cxf", "/ESBService/test2");
//
//            }else {
//                logger.error("未知的ServiceID[{}]",serverId);
//                //requestWrapper.setAttribute("weizhisvericeid",);
//                //return false;
//            }
            path = path.replaceAll("/BONDService/cxf", "/EsbWebService/s"+serverId);
            //path = path.replaceAll("fsscApi/esb", "services/S"+serverId);
            //属于webservice请求,使用 子服务码 设置一个请求头
            logger.info("系统内部转换后路径[{}]",path);
            HeaderMapRequestWrapper headerMapRequestWrapper = new HeaderMapRequestWrapper(request);
            headerMapRequestWrapper.addHeader("SOAPAction","");
            headerMapRequestWrapper.getRequestDispatcher(path).forward(headerMapRequestWrapper, response);
            logger.info("WebserverHandlerInterceptor|调用结束");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("-------");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("==========");
    }

    public String getServiceId(String filetext){
        String str ="";
        Pattern p = Pattern.compile("(?<=\\ServiceID>)[^\\</]+");
        Matcher m = p.matcher(filetext);
        while(m.find()) {
            String str2 = m.group(0);
            if (StringUtils.isNotEmpty(str2)){
                //去掉特殊字符，空格 换行
                str2 = str2.replace("\r\n","");
                if (StringUtils.isNotEmpty(str2)&&StringUtils.isNotEmpty(str2.trim())){
                    str = str2;
                }
            }
        }
        return  str;
    }
    public String getSvcScn(String filetext){
        String str ="";
        Pattern p = Pattern.compile("(?<=\\SvcScn>)[^\\</]+");
        Matcher m = p.matcher(filetext);
        while(m.find()) {
            String str2 = m.group(0);
            if (StringUtils.isNotEmpty(str2)){
                //去掉特殊字符，空格 换行
                str2 = str2.replace("\r\n","");
                if (StringUtils.isNotEmpty(str2)&&StringUtils.isNotEmpty(str2.trim())){
                    str = str2;
                }
            }
        }
        return  str;
    }
}
